<?php
// 引入mysql.php
include('./mysql.php');
// 获取ajax请求的函数
$fn = $_GET['fn'];  // $fn=get
$fn();  // add()   // $fn()===get()
// 添加的函数
function add()
{
  // 1 获取参数
  $title = $_GET['title'];
  $pos = $_GET['pos'];
  $idea = $_GET['idea'];
  // 2 拼接sql
  $sql = "insert into problem values(null,'$title','$pos','$idea')";
  //echo $sql;  // 拼接完成要输出验证
  // 3 判断执行结果,然后回
  $res = query($sql);
  if ($res == 1) {
    echo json_encode([
      'stateCode' => 200,
      'state' => 'success',
      'data' => []
    ]);
  } else {
    echo json_encode([
      'stateCode' => 201,
      'state' => 'failer',
      'data' => []
    ]);
  }
}
// 删除的函数
function del()
{
  $id = $_GET['id'];
  $sql = 'delete from problem where id=' . $id;
  $res = query($sql);
  if ($res == 1) {
    echo json_encode([
      'stateCode' => 200,
      'state' => 'success',
      'data' => ''
    ]);
  } else {
    echo json_encode([
      'stateCode' => 201,
      'state' => 'failer',
      'data' => ''
    ]);
  }
}
// 获取数据的函数
function get()
{
  // 分页的实现
  // 接受页码数
  $pageSize = $_GET['psize'];
  // 每页显示数
  $num = 3;
  // 获取总数据
  $sql1 = 'select count(*) cou from problem';
  $res = select($sql1);
  $count = $res[0]['cou'];
  // 计算总页数
  $pageCount = ceil($count / $num);
  // 起始位置计算
  $start = ($pageSize - 1) * $num;
  $sql = "select * from problem order by id limit $start,$num";
  $res = select($sql);
  // 重新构造数组
  $res = ['pageData' => $res, 'pcount' => $pageCount];
  echo json_encode([
    'stateCode' => 200,
    'state' => 'success',
    'data' => $res
  ]);
}
// 修改的函数
function update()
{
  $id = $_GET['id'];
  $idea = $_GET['idea'];
  $title = $_GET['title'];
  $pos = $_GET['pos'];
  $sql = "update problem set title = '$title',pos = '$pos',idea = '$idea'   where id = $id";
  // echo $sql;
  $res = query($sql);
  if ($res == 1) {
    echo json_encode([
      'stateCode' => 200,
      'state' => 'success',
      'data' => ''
    ]);
  } else {
    echo json_encode([
      'stateCode' => 201,
      'state' => 'failer',
      'data' => ''
    ]);
  }
}
